package com.cskaoyan.mall.service;


import com.cskaoyan.mall.bean.Category;
import com.cskaoyan.mall.bean.vo.CategoryL1VO;
import com.cskaoyan.mall.bean.vo.CategoryLevelOne;
import com.cskaoyan.mall.bean.vo.CategoryLevelTwo;
import com.cskaoyan.mall.bean.vo.CategoryVO;
import com.cskaoyan.mall.bean.vo.*;
import com.cskaoyan.mall.mapper.CategoryMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @Author: dyj
 * @Date: 2021/1/10 19:19
 * @Description
 */
@Service
public class CategoryServiceImpl implements CategoryService{

    @Autowired
    CategoryMapper categoryMapper;

    @Override
    public List<CategoryLevelOne> selectAll() {
        return categoryMapper.selectAll();
    }

    @Override
    public List<CategoryL1VO> selectLevelOne() {
        return categoryMapper.selectLevelOne();
    }

    @Override
    public CategoryVO insertSelective(Category category) {

        // 设置添加时间和更新时间
        String nowtime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        category.setAddTime(nowtime);
        category.setUpdateTime(nowtime);

        // 插入的同时  useGenerateKeys  获得自增长id
        categoryMapper.insertSelective(category);

        return new CategoryVO(category);
    }

    @Override
    public void updateCategory(Category category) {
        // 更新时间
        String nowtime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        category.setUpdateTime(nowtime);
        categoryMapper.updateByPrimaryKeySelective(category);
    }

    @Transactional
    @Override
    public void deleteCategory(CategoryLevelOne categoryLevelOne) {

        // TODO 优化
        // 一二级类目都直接根据id删除
        categoryMapper.deleteByPrimaryKey(categoryLevelOne.getId());

        // 有二级目录则遍历删除
        if (categoryLevelOne.getChildren() != null) {
            for (CategoryLevelTwo categoryLevelTwo : categoryLevelOne.getChildren()) {
                categoryMapper.deleteByPrimaryKey(categoryLevelTwo.getId());
            }
        }
    }

    public List<GoodsCategoryVO> queryAllGoodsCategory() {
        List<GoodsCategoryVO> goodsCategoryVOS = categoryMapper.selectAllGoodsParentCategory();
        for (GoodsCategoryVO goodsCategoryVO : goodsCategoryVOS) {
            List<GoodsChildrenCategoryVO> goodsChildrenCategoryVOS = categoryMapper.selectAllGoodsChildrenCategory(goodsCategoryVO);
            goodsCategoryVO.setChildren(goodsChildrenCategoryVOS);
        }
        return goodsCategoryVOS;
    }
}
